package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.constants.QueueConstants;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.OrderProblemCommitRequest;
import com.ytjj.qmyx.supplychain.common.model.request.OrderProblemListRequest;
import com.ytjj.qmyx.supplychain.common.model.request.OrderProblemReplyRequest;
import com.ytjj.qmyx.supplychain.common.model.response.OrderInteractRecords;
import com.ytjj.qmyx.supplychain.common.model.response.OrderProblemDetailResponse;
import com.ytjj.qmyx.supplychain.common.model.response.OrderProblemExportResponse;
import com.ytjj.qmyx.supplychain.common.model.response.OrderProblemListResponse;
import com.ytjj.qmyx.supplychain.common.utils.DateUtil;
import com.ytjj.qmyx.supplychain.mapper.ExpressRecordsMapper;
import com.ytjj.qmyx.supplychain.mapper.OrdersMapper;
import com.ytjj.qmyx.supplychain.mapper.YxOrderInteractRecordsMapper;
import com.ytjj.qmyx.supplychain.mapper.YxOrderProblemMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderProblemService{

    @Resource
    private YxOrderProblemMapper orderProblemMapper;

    @Resource
    private YxOrderInteractRecordsMapper orderInteractRecordsMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private ExpressRecordsMapper expressRecordsMapper;

    @Resource
    private ExpressDicService expressDicService;

    @Resource(name = "guchuangRabbitTemplate")
    private RabbitTemplate guchuangRabbitTemplate;

//    @Resource(name = "jumaiduoRabbitTemplate")
//    private RabbitTemplate jumaiduoRabbitTemplate;
//
//    @Resource(name = "yiquanRabbitTemplate")
//    private RabbitTemplate yiquanRabbitTemplate;
//
//    @Resource(name = "zxlpRabbitTemplate")
//    private RabbitTemplate zxlpRabbitTemplate;
//
//    @Resource(name = "ygyxRabbitTemplate")
//    private RabbitTemplate ygyxRabbitTemplate;
//
//    @Resource(name = "yxhdRabbitTemplate")
//    private RabbitTemplate yxhdRabbitTemplate;
//
//    @Resource(name = "jckjRabbitTemplate")
//    private RabbitTemplate jckjRabbitTemplate;


    public Integer commitProblem(OrderProblemCommitRequest request) {
        Integer result ;
        if (!StringUtils.isEmpty(request.getChildOrderNo())) {
            List<YxOrderProblem> yxOrderProblems = orderProblemMapper.selectByChildOrderNo(request.getChildOrderNo());
            if (CollectionUtils.isEmpty(yxOrderProblems)) {
                //订单问题
                result =  saveOrderProblem(request);
            } else {
                result = yxOrderProblems.get(0).getId();
            }
        } else {
            //订单问题
            result =  saveOrderProblem(request);
        }

        //订单沟通记录
        YxOrderInteractRecords  records = new YxOrderInteractRecords();
        records.setContentText(request.getContentText());
        records.setContentImg(request.getContentImg());
        records.setContentVideo(request.getContentVideo());
        records.setContentFile(request.getContentFile());
        records.setReplyUser(request.getCommitUser());
        records.setReplyRole(1);
        records.setProblemId(result);
        records.setReceiveUser(request.getReceiveUser());
        records.setReasonType(request.getReasonType());
        records.setReplyTime(new Date());
        records.setProblemClassify(request.getProblemClassify());
        records.setChildOrderNo(request.getChildOrderNo());
        orderInteractRecordsMapper.insert(records);
       return result;
    }

    private Integer saveOrderProblem(OrderProblemCommitRequest request) {
        YxOrderProblem orderProblem = new YxOrderProblem();
        //订单问题
        orderProblem.setBankerId(request.getBankerId());
        orderProblem.setChildOrderNo(request.getChildOrderNo());
        orderProblem.setCommitUser(request.getCommitUser());
        orderProblem.setCommitTime(new Date());
        orderProblem.setStatus(1);
        orderProblem.setDealStatus(1);
        orderProblem.setSupplyProductId(request.getSupplyProductId());
        orderProblem.setProblemType(request.getProblemType());
        orderProblemMapper.insert(orderProblem);
        return orderProblem.getId();
    }

    public YxOrderInteractRecords replyProblem(OrderProblemReplyRequest request) {
        if (StringUtils.isEmpty(request.getContentImg()) &&  StringUtils.isEmpty(request.getContentVideo())
                && StringUtils.isEmpty(request.getContentText())) {
            throw new ApiException("提交问题的内容、图片、视频不能同时为空!!!");
        }
        YxOrderProblem orderProblem = orderProblemMapper.selectById(request.getProblemId());
        if (null !=orderProblem) {
            //订单沟通记录
            YxOrderInteractRecords  records = new YxOrderInteractRecords();

            //如果是跟单回复，不选择回复人，默认选择最新回复人
            if (StringUtils.isEmpty(request.getReceiveUserName()) && request.getReplyRole() ==2) {
                List<OrderInteractRecords> orderInteractRecords = orderInteractRecordsMapper.selectAllByProblemId(request.getProblemId(), 1);
                orderInteractRecords = orderInteractRecords.stream().sorted(Comparator.comparing(OrderInteractRecords::getId).reversed()).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(orderInteractRecords)) {
                    records.setReceiveUser(orderInteractRecords.get(0).getReplyUser());
                }
            } else {
                records.setReceiveUser(request.getReceiveUserName());
            }
            //供应商回复，默认回复人是最新客服
            if (request.getReplyRole() ==3) {
                List<OrderInteractRecords> orderInteractRecords = orderInteractRecordsMapper.selectAllByProblemId(request.getProblemId(), 1);
                orderInteractRecords = orderInteractRecords.stream().sorted(Comparator.comparing(OrderInteractRecords::getId).reversed()).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(orderInteractRecords)) {
                    request.setReceiveUserName(orderInteractRecords.get(0).getReplyUser());
                }
            }

            records.setContentText(request.getContentText());
            records.setContentImg(request.getContentImg());
            records.setContentVideo(request.getContentVideo());
            records.setReplyUser(request.getCommitUserName());
            records.setReplyRole(request.getReplyRole());
            records.setReplyTime(new Date());
            records.setProblemId(request.getProblemId());
            records.setProblemClassify(request.getProblemClassify());
            records.setReasonType(request.getReasonType());
            records.setChildOrderNo(request.getChildOrderNo());
            records.setDocumentaryProblemType(request.getDocumentaryProblemType());
            records.setContentFile(request.getContentFile());
            //修改问题状态
            if (orderProblem.getStatus() == 2) {
                orderProblemMapper.updateStatus(request.getProblemId(),1);
            }
            //更新问题跟单处理状态
            if (request.getReplyRole() ==1) {
                orderProblemMapper.updateDealStatus(request.getProblemId(),1);
            }

            //更新供应商处理状态
            if (request.getReplyRole() ==1 || request.getReplyRole() ==2) {
                orderProblemMapper.updateProblemBankerDealStatus(request.getProblemId(),1);
            }

            orderInteractRecordsMapper.insert(records);
            if(request.getReplyRole() ==3  ) {
                //供应商订单问题回复
                if(request.getProblemType() == 1) {
                    String beginChildOrderNo = request.getChildOrderNo().substring(0, 1);
                    if ("Z".equals(beginChildOrderNo)) {
                        sendOrderProblemMessage(guchuangRabbitTemplate,request);
                    }
//                    else if ("D".equals(beginChildOrderNo) ) {
//                        sendOrderProblemMessage(jumaiduoRabbitTemplate,request);
//                    } else if ("F".equals(beginChildOrderNo)) {
//                        sendOrderProblemMessage(yiquanRabbitTemplate,request);
//                    } else if("H".equals(beginChildOrderNo)) {
//                        sendOrderProblemMessage(zxlpRabbitTemplate,request);
//                    } else if ("O".equals(beginChildOrderNo)) {
//                        sendOrderProblemMessage(ygyxRabbitTemplate,request);
//                    } else if ("Q".equals(beginChildOrderNo)) {
//                        sendOrderProblemMessage(yxhdRabbitTemplate,request);
//                    } else if ("S".equals(beginChildOrderNo)) {
//                        sendOrderProblemMessage(jckjRabbitTemplate,request);
//                    }
                    //供应商商品问题回复
                } else if (request.getProblemType() == 2) {
                    sendOrderProblemMessage(guchuangRabbitTemplate,request);
                }

            }
            return records;
        }
        return null;
    }

    public int finishProblem(Integer id) {
        return orderProblemMapper.updateStatus(id, 2);
    }

    private void sendOrderProblemMessage(RabbitTemplate rabbitTemplate, OrderProblemReplyRequest request) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("commitUser",request.getCommitUser());
        requestMap.put("content",request.getContentText());
        requestMap.put("problemId",request.getProblemId());
        requestMap.put("commitTime",new Date());
        requestMap.put("status",0);
        requestMap.put("problemStatus",1);
        requestMap.put("childOrderNo",request.getChildOrderNo());
        requestMap.put("receiveUserName",request.getReceiveUserName());
        requestMap.put("replyRole",request.getReplyRole());
        rabbitTemplate.convertAndSend(QueueConstants.ORDER_PROBLEM_REPLY, JSON.toJSONString(requestMap));
    }


    public CommonPage<OrderProblemListResponse> orderProblemList(OrderProblemListRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<OrderProblemListResponse> list =  orderProblemMapper.orderProblemList(request);
        if (!CollectionUtils.isEmpty(list)) {
            List<String> childOrderNoList = list.stream().filter(item -> null != item.getChildOrderNo()).map(OrderProblemListResponse::getChildOrderNo).collect(Collectors.toList());
            List<YxOrdersPay> yxOrdersPays = null;
            List<YxExpressRecords> yxExpressRecords = new ArrayList<>();
            if (!CollectionUtils.isEmpty(childOrderNoList)) {
                yxOrdersPays = ordersMapper.queryAllByChildOrderNos(childOrderNoList);
                yxExpressRecords = expressRecordsMapper.queryByChildOrderNoList(childOrderNoList);
            }
            List<String> expressCodeList = list.stream().filter(item -> null != item.getExpressCode()).map(OrderProblemListResponse::getExpressCode).collect(Collectors.toList());
            //快递公司
            List<YxExpressDic> yxExpressDics = null;
            if (!CollectionUtils.isEmpty(expressCodeList)) {
                yxExpressDics = expressDicService.queryExpressDicListByExpressValues(expressCodeList);
            }
            for (OrderProblemListResponse orderProblemListResponse : list) {
                orderProblemListResponse.setIsPay(1);
                List<OrderInteractRecords> orderInteractRecords = orderInteractRecordsMapper.selectAllByProblemId(orderProblemListResponse.getId(), null);
                orderProblemListResponse.setRecordsList(orderInteractRecords);

                if (!CollectionUtils.isEmpty(yxExpressDics)) {
                    List<YxExpressDic> collect = yxExpressDics.stream().filter(item -> item.getExpressValue().equals(orderProblemListResponse.getExpressCode())).collect(Collectors.toList());
                    orderProblemListResponse.setExpressName(CollectionUtils.isEmpty(collect) ? "" : collect.get(0).getExpressKey());
                }

                if (!CollectionUtils.isEmpty(yxOrdersPays)) {
                    List<YxOrdersPay> collect = yxOrdersPays.stream().filter(item -> item.getChildOrderNo().equals(orderProblemListResponse.getChildOrderNo())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)) {
                        if ("aliPay-jsApi".equals(collect.get(0).getTradeType()) || "aliPay".equals(collect.get(0).getTradeType())) {
                            orderProblemListResponse.setPaySource("aliPay");
                        } else {
                            orderProblemListResponse.setPaySource("wx");
                        }
                    }
                }
                if(!CollectionUtils.isEmpty(yxExpressRecords)){
                    List<String> expressRecords = yxExpressRecords.stream().filter(item -> item.getChildOrderNo().equals(orderProblemListResponse.getChildOrderNo())).map(e -> e.getCompanyNo() + " " + e.getExpressEno()).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(expressRecords)){
                        orderProblemListResponse.setExpressRecordStr(String.join(",", expressRecords));
                    }
                }
            }

        }
        return CommonPage.restPage(list);
    }


    public OrderProblemDetailResponse orderProblemDetail(Integer id) {
        OrderProblemDetailResponse orderProblemDetailResponse = orderProblemMapper.queryDetail(id);
        if (null != orderProblemDetailResponse) {
            List<YxOrdersPay> yxOrdersPays = ordersMapper.queryAllByChildOrderNos(Lists.newArrayList(orderProblemDetailResponse.getChildOrderNo()));
            List<OrderInteractRecords> orderInteractRecords = orderInteractRecordsMapper.selectAllByProblemId(id, null);
            orderProblemDetailResponse.setRecordsList(orderInteractRecords);
            if (!CollectionUtils.isEmpty(yxOrdersPays)) {
                if ("aliPay-jsApi".equals(yxOrdersPays.get(0).getTradeType()) || "aliPay".equals(yxOrdersPays.get(0).getTradeType())) {
                    orderProblemDetailResponse.setPaySource("aliPay");
                } else {
                    orderProblemDetailResponse.setPaySource("wx");
                }
                if (!StringUtils.isEmpty(orderProblemDetailResponse.getExpressCode())) {
                    List<YxExpressDic> expressDicByExpressCode = expressDicService.queryExpressDicListByExpressValue(orderProblemDetailResponse.getExpressCode());
                    orderProblemDetailResponse.setExpressName(CollectionUtils.isEmpty(expressDicByExpressCode) ? "" : expressDicByExpressCode.get(0).getExpressKey());
                }
            }
        }
        return orderProblemDetailResponse;
    }

    public Integer updateDealStatus(Integer id, Integer dealStatus) {

        return orderProblemMapper.updateDealStatus(id,dealStatus);
    }

    public List<OrderProblemExportResponse> exportOrderProblemList(OrderProblemListRequest request) {
        List<OrderProblemExportResponse> list =  orderProblemMapper.exportOrderProblemList(request);
        if (!CollectionUtils.isEmpty(list) && request.getQueryType()!=null && request.getQueryType() == 4) {
            for (OrderProblemExportResponse response : list) {
                List<OrderInteractRecords> orderInteractRecords = orderInteractRecordsMapper.selectAllByProblemId(response.getId(), null);
                String content = null;
                if (!CollectionUtils.isEmpty(orderInteractRecords)) {
                    content = orderInteractRecords.stream().map(item -> item.getReplyUser() + " " + DateUtil.dateToStr(item.getReplyTime()) + " " + item.getContentText()).collect(Collectors.joining(" |"));
                }
                response.setContentText(content);
            }
        }
        return list;
    }

    public Integer updateProblemUrgent(Integer id, Integer isUrgent) {
        return orderProblemMapper.updateProblemUrgent(id,isUrgent);
    }

    public Integer updateProblemBankerDealStatus(Integer id, Integer bankerDealStatus) {
        return orderProblemMapper.updateProblemBankerDealStatus(id,bankerDealStatus);
    }
}
